﻿using System.Collections.Generic;
using EOS.Framework.Kernel;
using Microsoft.Practices.Unity;

namespace EOS.Framework.Web.Mvc
{
    public sealed class ContainerFactory : IContainerFactory
    {
        private Dictionary<string, int> _counts = new Dictionary<string, int>();

        public void StartRequest()
        {
            _counts.Clear();
        }

        /// <summary>
        /// Calculates the name of the internal.
        /// </summary>
        /// <param name="componentName">Name of the component.</param>
        /// <returns></returns>
        private string CalculateContainerName(string containerName)
        {
            string internalName = string.Empty;

            int componentNumber = 0;
            _counts.TryGetValue(containerName, out componentNumber);

            internalName = containerName + componentNumber;
            _counts[containerName] = componentNumber + 1;

            return internalName;
        }

        public IWebPage CreateWebPage(string name)
        {
            IWebPage webPage = null;
            try
            {
                webPage = Unity.Current.Resolve<IWebPage>(name.ToLower());
                webPage.Name = CalculateContainerName(name);
            }
            catch (ResolutionFailedException)
            {
            }
            
            return webPage;
        }

        public IWebPart CreateWebPart(string name)
        {
            IWebPart webPart = null;
            try
            {
                webPart = Unity.Current.Resolve<IWebPart>(name.ToLower());
                webPart.Name = CalculateContainerName(name);
            }
            catch (ResolutionFailedException)
            {
            }

            return webPart;
        }
    }
}
